package com.bwie.home.backstage.aop;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class CreateTokenAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public static final String TOKEN_PREFIX = "home:token:";

    @Pointcut("@annotation(com.bwie.home.backstage.aop.Token)")
    public void annotationPointcut() {
    }

    @Around("annotationPointcut()")
    public Object checkToken(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取接口中的参数
        // 例如：public R save(@RequestBody ClassifyEntity classify, HttpServletRequest request)
        Object[] args = joinPoint.getArgs();
        //获取头部的token
        HttpServletRequest arg = (HttpServletRequest) args[1];
        String token = arg.getHeader("token");
        //从redis中获取token
        String token1 = redisTemplate.opsForValue().get(TOKEN_PREFIX);
        //判断头部是否有传过来token
        if(token==null){
            String mes = "操作失败，没有获取到令牌";
            log.info(mes);
            throw new Exception(mes);
        }else if(!token.equals(token1)){//对比redis中的token和头部的token是否一致
            String mes = "提交失败,令牌不匹配";
            log.info(mes);
            throw new Exception(mes);
        }
        log.info("操作成功");
        return joinPoint.proceed();
    }

    /**
     * 当checkToken方法执行完毕并返回的时候开始执行
     */
    @AfterReturning("annotationPointcut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        redisTemplate.delete(TOKEN_PREFIX);
    }


}
